--手枪，步枪，机枪
--子弹，机枪子弹，起源弹
--材质包 homura_pistol

--② ammo:  1~3   (物品栏子弹)
--③ pro: anim/anim_magic/anim_magic_sp  (飞行子弹)  tail(尾迹)

--symbol: pistol gun hmg

local assets = 
{
    
    Asset("SOUNDPACKAGE", "sound/lw_homura.fev"),
    Asset("SOUND", "sound/lw_homura.fsb"), 
    Asset("ANIM", "anim/homura_pistol.zip"),
    
    Asset("ATLAS","images/inventoryimages/homura_pistol.xml"),
    Asset("ATLAS","images/inventoryimages/homura_gun.xml"),
    Asset("ATLAS","images/inventoryimages/homura_hmg.xml"),
    Asset("ATLAS","images/inventoryimages/homura_rifle.xml"),
    Asset("ATLAS","images/inventoryimages/homura_gun_ammo1.xml"),
    Asset("ATLAS","images/inventoryimages/homura_gun_ammo2.xml"),
    Asset("ATLAS","images/inventoryimages/homura_gun_ammo3.xml"),
    Asset("ATLAS","images/inventoryimages/homura_ammochain.xml"),

    Asset("ANIM","anim/player_homura_gun.zip"),

    Asset("ANIM","anim/homura_weapon_buff.zip"),

    Asset("ANIM","anim/lavaarena_hit_sparks_fx.zip"),
}

local L = HOMURA_GLOBALS.LANGUAGE
local function quickset(prefab,name,desc_data,recipe)
    prefab = string.upper(prefab)
    STRINGS.NAMES[prefab] = name 
    for cha,desc in pairs(desc_data)do
        cha = string.upper(cha)
        STRINGS.CHARACTERS[cha].DESCRIBE[prefab] = desc
    end
    STRINGS.RECIPE_DESC[prefab] = recipe
end
if HOMURA_GLOBALS.LANGUAGE then
    quickset("homura_gun_ammo1","Bullets",
        {
            generic = "Bullets for pistols and rifles",
        },"Bullets for pistols and rifles")
    quickset("homura_gun_ammo2","Machine gun bullets",
        {
            generic = "Bullets for machine gun",
        },"Bullets for machine gun")
    quickset("homura_gun_ammo3","Origination",
        {
            generic = "",
        },"Deal significant damage to witches.")
    quickset("homura_pistol","Desert eagle",
        {
            generic = "The power of this pistol cannot be underestimated"
        },"The most popular one")
    quickset("homura_gun","SCAR-L",
        {
            generic = "It reminds me of game by Bluehole."
        },"A kind of ssault rifle")
    quickset("homura_hmg","RPK74",
        {
            generic = "It't a bit heavy..."
        },"Fire suppression!")
    quickset("homura_rifle", "AWM",
        {
            generic = "I'm a sniper!",
        },"Become a sniper.")
    quickset('homura_ammochain', 'Ammunition Belt',
        {
            generic = 'Use it to link bullets.'
        },'Use it to link bullets.')

else
    quickset("homura_gun_ammo1","子弹",
        {
            generic = "可以用在手枪和步枪上",
            homura_1 = "没有它, 我的枪就毫无威力了",
        },"biu!")
    quickset("homura_gun_ammo2","机枪子弹",
        {
            generic = '可以用在机枪上',
            homura_1 = "适用于连发型的武器",
        },"biu!biu!biu!")
    quickset("homura_gun_ammo3","起源弹",
        {
            homura_1 = "你看这子弹...这好像是隔壁剧组的子弹?",
        },"对魔法生物造成重创。")
    quickset("homura_pistol","沙漠之鹰",
        {
            generic = "这手枪的威力不容小觑",
            homura_1 = "只要距离不远, 我就能轻松打中目标。",
        },"最著名的一款手枪")
    quickset("homura_gun","SCAR-L",
        {
            generic = "这让我想到了蓝洞公司的一个游戏",
            homura_1 = "看起来还不错.",
        },"可靠的半自动突击步枪")
    quickset("homura_hmg","RPK74",
        {
            generic = "我一梭子下去你可能会死",
            homura_1 = "唔, 有点沉。",
        },"火力压制!")
    quickset("homura_rifle", "AWM",
        {   
            generic = "我起了，一枪秒了，有什么好说的！"
        },"做一名狙击手")
    quickset('homura_ammochain','弹链',
        {
            generic = '一大串的, 跟鞭炮一样',
        },'一个把大量子弹串联在一起的装置')
end

local function CommonAmmo(num)
    local function fn()
        -- 机枪子弹更新兼容
        if num == 2 then
            return SpawnPrefab("homura_gun_ammo1")
        end
        
        local inst = CreateEntity()
        local trans = inst.entity:AddTransform()
        local anim = inst.entity:AddAnimState()
        local snd = inst.entity:AddSoundEmitter()
        local net   = inst.entity:AddNetwork()

        MakeInventoryPhysics(inst)
        MakeInventoryFloatable(inst, nil, 0.12, 0.9)

        anim:SetBank("ammo")
        anim:SetBuild("homura_pistol")
        anim:PlayAnimation(tostring(num))

        inst.entity:SetPristine()
        if not TheWorld.ismastersim then
            return inst
        end

        inst:AddComponent("inspectable")
        inst:AddComponent("homura_ammo")
        inst.projectilename = 'homura_projectile'..num

        inst:AddComponent("inventoryitem")
        inst.components.inventoryitem.atlasname = "images/inventoryimages/homura_gun_ammo"..num..".xml"

        inst:AddComponent("stackable")
        inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM

        MakeHauntableLaunch(inst)

        return inst
    end
    return Prefab("homura_gun_ammo"..num,fn,assets)
end

local function MakeAmmoChain()
    local inst = CreateEntity()
    local trans= inst.entity:AddTransform()
    local anim = inst.entity:AddAnimState()
    local net  = inst.entity:AddNetwork()

    anim:SetBank("ammo")
    anim:SetBuild("homura_pistol")
    anim:PlayAnimation("4")

    MakeInventoryPhysics(inst)

    inst.entity:SetPristine()
    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("inspectable")

    inst:AddComponent("inventoryitem")
    inst.components.inventoryitem.atlasname = "images/inventoryimages/homura_ammochain.xml"

    return inst
end

local function OnHit(inst, owner, target)
    inst.components.homura_projectile:OnHit(inst, owner, target)
    inst:Remove()
end

local function OnMiss(inst,owner,target)
    local fx = SpawnPrefab('homura_miss_fx')
    if inst:HasTag('homuraTag_magicpro') then
        fx.AnimState:SetAddColour(1,0,1,0.7)
    end
    fx.Transform:SetPosition(inst:GetPosition():Get())
    inst:Remove()
end

local function CreateTail(colour)
    --本地特效
    local inst = CreateEntity()
    inst.entity:AddTransform()
    inst.entity:AddAnimState()

    inst.AnimState:SetBuild("homura_pistol")
    inst.AnimState:SetBank("pro")
    inst.AnimState:PlayAnimation("tail")
    inst.AnimState:SetOrientation(ANIM_ORIENTATION.OnGround)
    inst.AnimState:SetLayer(LAYER_BACKGROUND)
    inst.AnimState:SetSortOrder(3)

    if colour == 1 then
        inst.AnimState:SetBloomEffectHandle("shaders/anim.ksh")
        inst.AnimState:SetLightOverride(1)
        inst.AnimState:SetMultColour(1, 0.2, 0.8, 0.8)
    elseif colour == 2 then
        inst.AnimState:OverrideSymbol('tail', 'homura_pistol', 'tail_ice')
        inst.AnimState:SetMultColour(1, 1, 1, 0.3)
    elseif colour == 3 then
        inst.AnimState:SetMultColour(1, 1, 1, 0.3)
    elseif colour == 4 then
        inst.AnimState:SetMultColour(1, 1, 0.8, 0.5)
    end

    inst.AnimState:SetFinalOffset(-1)

    inst:AddTag("FX")
    inst:AddTag("NOCLICK")

    inst:AddComponent("colourtweener")

    inst.entity:SetCanSleep(false)
    inst.persists = false
    
    inst.components.colourtweener:StartTween({0,0,0,0},4*FRAMES,inst.Remove)

    return inst
end

local function UpdateTail(inst,tails)
    inst.colourID = inst.colourID or inst._tail_colour:value()
    if not(inst.colourID and inst.colourID >= 1 and inst.colourID <= 4 )then
        return
    end

    if not inst.entity:IsVisible() then
        return
    end

    local pos = inst:GetPosition()
    local rot = inst.Transform:GetRotation()
    local tail = CreateTail(inst.colourID)
    tail.Transform:SetPosition(pos:Get())
    tail.Transform:SetRotation(rot)

    if inst.lastpos and inst.lastrot then
        local pos2 = (pos + inst.lastpos)/2
        local rot2 = PUELLA_MOD_FN.DeltaAngle(inst.lastrot,rot)/2 + inst.lastrot 
        local tail2 = CreateTail(inst.colourID, true)
        tail2.Transform:SetPosition(pos2:Get())
        tail2.Transform:SetRotation(rot2)
    end

    inst.lastpos = pos
    inst.lastrot = rot

    local speed = 15
    if inst:HasTag('homuraTag_ignoretimemagic') then
        tail:AddTag('homuraTag_ignoretimemagic')
    end
end

local function pro_common(inst)
    inst._tail_colour = net_tinybyte(inst.GUID, 'homuraVar.ProjectileTail')
    inst:ListenForEvent("entitysleep", inst.Remove)
    
    inst:DoPeriodicTask(0, UpdateTail, nil, {})
end

local function pro_master(inst)
    inst.components.projectile:SetOnHitFn(OnHit)
    inst.components.projectile:SetOnMissFn(OnMiss)
    inst.components.projectile:SetHoming(false)
    inst.components.projectile:SetHitDist(1)

    inst:AddComponent('homura_projectile')
end

local function pro1(inst) --手枪射出的子弹
    --trans:SetScale(.8,.8,.8)
    inst.components.projectile:SetLaunchOffset(Vector3(0,1,0))
    pro_master(inst)
end

local function pro2(inst) --步枪射出的子弹
    --trans:SetScale(.8,.8,.8)
    inst.components.projectile:SetLaunchOffset(Vector3(1.3,1.1,0))
    pro_master(inst)
end

local function pro3(inst) --机枪射出的子弹
    --trans:SetScale(.8,.8,.8)
    inst.components.projectile:SetLaunchOffset(Vector3(1.7,1,0))
    pro_master(inst)
end

local function pro4(inst)
    inst.AnimState:SetMultColour(1,1,0.5,1)
    inst.components.projectile:SetLaunchOffset(Vector3(2.3,1,0))
    pro_master(inst)
end

local function OnLaunched(inst,attacker,target)
    inst.components.homura_weapon:OnLaunched(attacker)
end

local function CommonGunFn(name)
    local inst = CreateEntity()
    inst.entity:AddTransform() 
    inst.entity:AddAnimState() 
    inst.entity:AddSoundEmitter()
    inst.entity:AddNetwork()

    MakeInventoryPhysics(inst)

    inst.AnimState:SetBuild("homura_pistol")
    inst.AnimState:SetBank(name)
    inst.AnimState:PlayAnimation("idle")

    MakeInventoryFloatable(inst, "large", 0.5, 0.6)

    inst:AddTag("_named")
    inst:AddTag("_homura_focus")
    inst:AddTag("homuraTag_gun")

    inst.projectiledelay = FRAMES

    inst.entity:SetPristine()
    if not TheWorld.ismastersim then
        return inst
    end

    inst:RemoveTag("_named")
    inst:RemoveTag("_homura_focus")

    inst:AddComponent("inspectable")

    --inst.components.container.onopenfn = function(i) i.SoundEmitter:PlaySound("") end
    --inst.components.container.onclosefn = function(i) i.SoundEmitter:PlaySound("") end

    inst:AddComponent("inventoryitem")
    inst.components.inventoryitem.atlasname = "images/inventoryimages/homura_"..name..".xml"
 
    inst:AddComponent("equippable")
    inst.components.equippable:SetOnEquip(function(_,owner)
        owner.AnimState:OverrideSymbol("swap_object","homura_pistol",'swap_'..name)
        owner.AnimState:Show("arm_carry")
        owner.AnimState:Hide("arm_normal")
    end)
    inst.components.equippable:SetOnUnequip(function(_,owner)
        owner.AnimState:ClearOverrideSymbol("swap_object")
        owner.AnimState:Hide("arm_carry")
        owner.AnimState:Show("arm_normal") 
    end)

    inst:AddComponent("container")
    inst.components.container:WidgetSetup("homura_"..name)

    inst:AddComponent("weapon")
    inst.components.weapon:SetOnProjectileLaunched(OnLaunched)
    
    inst:AddComponent("homura_weapon")
    inst.components.homura_weapon.projectile = "homura_projectile_"..name
    inst.components.homura_weapon.ammo_prefabname = "homura_gun_ammo1"
    inst.components.homura_weapon:SetBasicPara(HOMURA_GLOBALS[name:upper()])
    
    inst:AddComponent('named')

    MakeHauntableLaunch(inst)
    
    return inst
end

local function PistolFn()
    local inst = CommonGunFn("pistol")

    inst.components.floater:SetSize("med")

    return inst
end

local function GunFn()
    local inst = CommonGunFn("gun")

    return inst
end


local function HMGFn()
    local inst = CommonGunFn("hmg")
    
    inst.projectiledelay = nil

    return inst
end

local function OnBuilt(inst)
    if inst.components.container then
        if next(inst.components.container:GetItemByName("homura_weapon_buff_eye_lens", 1)) == nil then
            inst.components.container:GiveItem(SpawnPrefab("homura_weapon_buff_eye_lens"), 1)
        end
    end
end

local function RifleFn()
    local inst = CommonGunFn("rifle")

    if TheWorld.ismastersim then
        inst.OnBuilt = OnBuilt
        inst:DoTaskInTime(0, OnBuilt)
    end

    return inst
end

local function missfx()
    local inst = CreateEntity()
    local trans = inst.entity:AddTransform()
    local anim = inst.entity:AddAnimState()
    local snd = inst.entity:AddSoundEmitter()
    local net   = inst.entity:AddNetwork()

    anim:SetBuild("lavaarena_hit_sparks_fx")
    anim:SetBank("hits_sparks")
    anim:PlayAnimation("hit_"..math.random(5))
    anim:SetLightOverride(1)
    anim:SetMultColour(1,1,0.5,1)
    anim:SetBloomEffectHandle("shaders/anim.ksh")
    
    snd:PlaySound('lw_homura/sfx/miss'..math.random(2), nil, 0.5)

    trans:SetScale(0.5,0.5,0.5)
  
    inst:AddTag('FX')
    inst:AddTag('NOCLICK')
    inst:AddTag('NOBLOCK')
 
    inst.entity:SetPristine()
 
    if not TheWorld.ismastersim then
        return inst
    end
   
    inst:ListenForEvent("animover", inst.Remove)

    return inst
end


return 
PUELLA_MOD_FN.MakeProjectile( "homura_projectile_pistol", "pro","homura_pistol",
 "anim",true ,1, nil, assets, pro1, pro_common),
PUELLA_MOD_FN.MakeProjectile( "homura_projectile_gun", "pro","homura_pistol",
 "anim",true ,2, nil, assets, pro2, pro_common),
PUELLA_MOD_FN.MakeProjectile( "homura_projectile_hmg", "pro","homura_pistol",
 "anim",true ,4, nil, assets, pro3, pro_common),
PUELLA_MOD_FN.MakeProjectile("homura_projectile_rifle", "pro", "homura_pistol", "anim_light", true, 8, nil ,assets, pro4, pro_common),
Prefab( "common/inventory/homura_pistol", PistolFn,assets),
Prefab( "common/inventory/homura_gun", GunFn,assets),
Prefab( "common/inventory/homura_hmg", HMGFn,assets),
Prefab("homura_rifle", RifleFn,assets),
CommonAmmo(1),CommonAmmo(2),CommonAmmo(3), --homura_gun_ammo1~3
Prefab('homura_ammochain', MakeAmmoChain),
Prefab('homura_miss_fx',missfx,assets)

